#!/bin/bash

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        echo "macos"
    elif [[ -f /etc/debian_version ]]; then
        echo "debian"
    else
        echo "unknown"
    fi
}

# 检查是否为普通用户（非root）
check_user() {
    if [ "$EUID" -eq 0 ]; then
        log_error "请使用普通用户运行此脚本"
        exit 1
    fi
}

# 检查必要的命令
check_command() {
    if ! command -v "$1" &> /dev/null; then
        return 1
    fi
    return 0
}

# 安装基础依赖
install_dependencies() {
    local os_type=$(detect_os)
    log_info "检测到操作系统: $os_type"

    case $os_type in
        "macos")
            log_info "在macOS上安装依赖..."
            if ! check_command "brew"; then
                log_info "安装Homebrew..."
                /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
            fi
            # macOS默认已安装zsh，只需要安装curl和git
            brew update
            brew install curl git
            ;;
        "debian")
            log_info "在Debian/Ubuntu上安装依赖..."
            sudo apt update -qq
            sudo apt install -y -qq curl git zsh
            ;;
        *)
            log_error "不支持的操作系统: $os_type"
            log_info "此脚本仅支持 Debian/Ubuntu 和 macOS"
            exit 1
            ;;
    esac

    log_success "基础工具安装完成"
}

# 安装Oh My Zsh
install_oh_my_zsh() {
    log_info "安装Oh My Zsh..."
    
    if [ -d "$HOME/.oh-my-zsh" ]; then
        log_warning "Oh My Zsh已存在，跳过安装"
        return 0
    fi
    
    # 尝试多个源，提高成功率
    local install_urls=(
        "https://gitee.com/allenjia09/ohmyzsh/raw/master/tools/install.sh"
        "https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh"
        "https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh"
    )
    
    for url in "${install_urls[@]}"; do
        log_info "尝试从 $url 安装..."
        if sh -c "$(curl -fsSL $url)" "" --unattended 2>/dev/null; then
            log_success "Oh My Zsh安装成功"
            return 0
        else
            log_warning "从 $url 安装失败，尝试下一个源..."
        fi
    done
    
    log_error "所有Oh My Zsh安装源都失败了"
    exit 1
}

# 安装插件
install_plugins() {
    log_info "安装Zsh插件..."
    
    # 定义插件目录
    local ZSH_CUSTOM=${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}
    
    if [ ! -d "$ZSH_CUSTOM" ]; then
        log_error "Oh My Zsh custom目录不存在: $ZSH_CUSTOM"
        exit 1
    fi
    
    # 插件列表：名称|主源|备用源
    local plugins=(
        "zsh-autosuggestions|https://gitee.com/allenjia09/zsh-autosuggestions.git|https://github.com/zsh-users/zsh-autosuggestions.git"
        "zsh-syntax-highlighting|https://gitee.com/allenjia09/zsh-syntax-highlighting.git|https://github.com/zsh-users/zsh-syntax-highlighting.git"
        "zsh-completions|https://gitee.com/allenjia09/zsh-completions.git|https://github.com/zsh-users/zsh-completions.git"
    )
    
    for plugin_info in "${plugins[@]}"; do
        IFS='|' read -r plugin_name primary_url backup_url <<< "$plugin_info"
        local plugin_dir="$ZSH_CUSTOM/plugins/$plugin_name"
        
        if [ -d "$plugin_dir" ]; then
            log_warning "插件 $plugin_name 已存在，跳过安装"
            continue
        fi
        
        log_info "安装插件: $plugin_name"
        
        # 先尝试主源，再尝试备用源
        if git clone --depth=1 -q "$primary_url" "$plugin_dir" 2>/dev/null; then
            log_success "插件 $plugin_name 安装成功 (主源)"
        elif git clone --depth=1 -q "$backup_url" "$plugin_dir" 2>/dev/null; then
            log_success "插件 $plugin_name 安装成功 (备用源)"
        else
            log_error "插件 $plugin_name 安装失败"
            # 不退出，继续安装其他插件
        fi
    done
}

# 配置.zshrc
configure_zshrc() {
    log_info "配置.zshrc文件..."

    local zshrc_file="$HOME/.zshrc"

    # 备份现有配置
    if [ -f "$zshrc_file" ]; then
        local backup_file="$HOME/.zshrc.bak-$(date +%Y%m%d-%H%M%S)"
        cp "$zshrc_file" "$backup_file"
        log_info "已备份现有配置到: $backup_file"
    fi

    # 更新插件配置
    if [ -f "$zshrc_file" ]; then
        # 使用更安全的sed命令，兼容不同的sed版本
        if grep -q "^plugins=" "$zshrc_file"; then
            # 创建临时文件避免sed的兼容性问题
            sed 's/^plugins=.*/plugins=(git zsh-autosuggestions zsh-syntax-highlighting zsh-completions)/' "$zshrc_file" > "$zshrc_file.tmp"
            mv "$zshrc_file.tmp" "$zshrc_file"
        else
            echo 'plugins=(git zsh-autosuggestions zsh-syntax-highlighting zsh-completions)' >> "$zshrc_file"
        fi
    fi

    # 添加优化配置
    cat << 'EOF' >> "$zshrc_file"

# === Zsh优化配置 ===
# 自动切换目录
setopt autocd
# 自动纠错
setopt correct_all
# 历史记录设置
HISTSIZE=100000
SAVEHIST=100000
HISTFILE=~/.zsh_history
setopt hist_ignore_all_dups
setopt hist_ignore_space
setopt share_history

# 补全设置
autoload -U compinit && compinit
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

# 常用别名
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

# 根据系统类型设置特定别名
if [[ "\$OSTYPE" == "darwin"* ]]; then
    alias ls='ls -G'
else
    alias ls='ls --color=auto'
fi

# 如果存在现代化工具，使用它们
if command -v exa &> /dev/null; then
    alias ls='exa'
    alias ll='exa -alF'
    alias la='exa -A'
    alias l='exa -CF'
fi

if command -v bat &> /dev/null; then
    alias cat='bat'
fi
EOF

    log_success ".zshrc配置完成"
}

# 设置默认Shell
set_default_shell() {
    log_info "设置zsh为默认shell..."

    local zsh_path=$(which zsh)

    if [ -z "$zsh_path" ]; then
        log_error "找不到zsh可执行文件"
        exit 1
    fi

    log_info "找到zsh路径: $zsh_path"

    # 检查zsh是否已在/etc/shells中
    if ! grep -q "^$zsh_path$" /etc/shells 2>/dev/null; then
        log_info "将zsh添加到/etc/shells..."
        echo "$zsh_path" | sudo tee -a /etc/shells > /dev/null
        log_success "已添加zsh到/etc/shells"
    else
        log_info "zsh已在/etc/shells中"
    fi

    # 更改默认shell
    local current_shell
    if command -v getent &> /dev/null; then
        current_shell=$(getent passwd "$USER" | cut -d: -f7)
    else
        current_shell="$SHELL"
    fi

    if [ "$current_shell" != "$zsh_path" ]; then
        log_info "当前默认shell: $current_shell"
        log_info "正在设置zsh为默认shell..."
        if chsh -s "$zsh_path"; then
            log_success "默认shell已设置为zsh"
            log_warning "需要重新登录或重启终端才能生效"
        else
            log_error "设置默认shell失败"
            exit 1
        fi
    else
        log_success "zsh已经是默认shell"
    fi
}

# 显示完成信息
show_completion_info() {
    local os_type=$(detect_os)

    echo ""
    log_success "=== Zsh安装配置完成 ==="
    echo ""
    log_info "启用zsh的方法 (选择其中一种):"
    echo "  1. exec zsh                    # 立即切换到zsh (推荐)"
    echo "  2. 重新登录或重启终端           # 使默认shell生效"
    echo "  3. source ~/.zshrc             # 重新加载配置"
    echo ""
    log_info "验证安装:"
    echo "  - 运行 'echo \$SHELL' 查看当前shell"
    echo "  - 运行 'zsh --version' 查看zsh版本"
    echo ""

    # 根据操作系统推荐不同的工具
    log_info "建议安装的额外工具:"
    case $os_type in
        "macos")
            echo "  - exa (现代化ls):     brew install exa"
            echo "  - bat (现代化cat):    brew install bat"
            echo "  - fd (现代化find):    brew install fd"
            echo "  - fzf (模糊搜索):     brew install fzf"
            ;;
        "debian")
            echo "  - exa (现代化ls):     sudo apt install exa"
            echo "  - bat (现代化cat):    sudo apt install bat"
            echo "  - fd-find (现代化find): sudo apt install fd-find"
            echo "  - fzf (模糊搜索):     sudo apt install fzf"
            ;;
        *)
            echo "  - exa, bat, fd, fzf 等现代化命令行工具"
            ;;
    esac

    echo ""
    log_warning "提示: 首次启动zsh可能需要几秒钟来初始化插件"
}

# 主函数
main() {
    log_info "开始安装和配置Zsh..."

    # 检查用户权限
    check_user

    # 安装依赖
    install_dependencies

    # 安装Oh My Zsh
    install_oh_my_zsh

    # 安装插件
    install_plugins

    # 配置.zshrc
    configure_zshrc

    # 设置默认shell
    set_default_shell

    # 显示完成信息
    show_completion_info
}

# 运行主函数
main "$@"
